/*******************************************************************************
** CopyRight (c) 2005-2008 SKY-MOBI Ltd. All rights reserved.
** Filename:  mem_mgr.c
** Creator:   huangXiaoHua
** Version:   0.0
** Date:      
** Description:
 *******************************************************************************/

#include "mrc_base.h"
#include "mem_mgr.h"

 int32 MemMgr_Init(MEM_MGR_T*xpm, uint16 len, uint16 step, uint16 itemSize)
{
	xpm->item = mrc_malloc(itemSize*len);
	if (!xpm->item){
		return MR_FAILED;
	} 
	mrc_memset(xpm->item, 0, itemSize*len);
	
	xpm->len = 0;
	xpm->bufLen = len;
	xpm->stepLen = step;
	return MR_SUCCESS;
}


 void MemMgr_ReSet(MEM_MGR_T* xpm, uint16 itemSize)
{
	mrc_memset(xpm->item, 0, itemSize*xpm->bufLen);
	xpm->len = 0;
}
 
 int32 MemMgr_AdjustLen(MEM_MGR_T* pm, int32 len, int32 offset, uint16 itemSize)
{
	if((pm->len + len) > pm->bufLen){
		uint8* tempBuf;
		int32 addLen = ((pm->bufLen + pm->stepLen) > (pm->len + len)) ?  pm->stepLen : (pm->len + len -pm->bufLen);
		tempBuf = mrc_malloc((pm->bufLen + addLen)*itemSize);
		if(!tempBuf ){
			return MR_FAILED;
		}

		pm->bufLen = pm->bufLen + addLen;
		memcpy(tempBuf, pm->item, (offset*itemSize));
		memcpy(tempBuf+(offset+len)*itemSize, (uint8*)pm->item+offset*itemSize, 
			(pm->len -offset)*itemSize);
		pm->len  += (uint16)len;
		mrc_free(pm->item);
		pm->item = (void*)tempBuf;
		return MR_SUCCESS;
	}
	memmove((uint8*)pm->item+(offset+len)*itemSize, (uint8*)pm->item+offset*itemSize, 
		(pm->len-offset)*itemSize);
	pm->len += (uint16)len;
	return MR_SUCCESS;
}

 void MemMgr_RemoveItem(MEM_MGR_T* pm, int32 offset, int32 size)
{
	memmove((uint8*)pm->item+offset*size, (uint8*)pm->item+(offset+1)*size, (pm->len-(offset+1))*size);
	pm->len--;
}

